import csv
import re

# 读取log文件并计算每个字符串出现的次数
with open('test.log', 'r') as log_file:
    log_data = log_file.read().splitlines()

# 使用字典来统计每个字符串出现的次数
log_count = {}
for line in log_data:
    # 去除首尾的空白字符
    line = line.strip()
    # 如果有进一步的格式调整需要，可以在此添加
    log_count[line] = log_count.get(line, 0) + 1

# 读取CSV文件并处理数据
with open('model.csv', 'r', newline='', encoding='utf-8') as csv_file:
    reader = csv.reader(csv_file)

    # 读取表头
    header = next(reader)
    # 结果数据包含表头，假设CSV文件头是 "Matched String,Expected Count,Actual Count,Pass or Fail"
    output_rows = [header]

    for row in reader:
        # 去除每一项的首尾空白字符并使用正则去掉附加引号
        matched_string = re.sub(r'^"|"$', '', row[0].strip())
        expected_count = int(row[1])

        # 使用正则表达式来匹配
        actual_count = sum(1 for line in log_data if re.search(re.escape(matched_string), line))

        # 根据实际次数与预期次数对比来确定结果
        result = 'Pass' if actual_count == expected_count else 'Fail'

        # 如果CSV中没有足够的列, 可以先填充到足够的列长度
        # 确保行有足够的列以防越界
        if len(row) < 4:
            # 插入缺失的空位或占位符 (0和"")
            row.extend([0] * (3 - len(row)) + [""])

        # 更新行数据
        row[2] = actual_count
        row[3] = result

        # 添加到结果数据行
        output_rows.append(row)

# 写入修改后的结果到新的CSV文件
with open('test_result.csv', 'w', newline='', encoding='utf-8') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerows(output_rows)

print("Results written to test_result.csv")

# 检查结果文件中所有行的测试结果
all_pass = True  # 初始假定所有测试都通过
with open('test_result.csv', 'r', newline='', encoding='utf-8') as csv_file:
    reader = csv.reader(csv_file)
    next(reader)  # 跳过表头

    for row in reader:
        if row[3] == 'Fail':
            all_pass = False
            break

# 返回整体结果
if all_pass:
    print("All tests passed: ")
    print("Pass")
else:
    print("One or more tests failed: ")
    print("Fail")
